#!/usr/bin/env python3
"""
颜色检测调试脚本
帮助诊断颜色检测问题
"""

import time
import pyautogui
from utils.dominant_color_detector import DominantColorDetector

def debug_demo_issue():
    """调试demo脚本的问题"""
    print("🔍 调试 demo_game_color_trigger.py 的问题")
    print("=" * 60)
    
    # 创建检测器
    detector = DominantColorDetector(region_size=200, k_clusters=3, cache_duration=0.1)
    
    print("步骤1: 设置目标颜色")
    print("请将目标颜色移动到屏幕中心，然后按回车...")
    input("按回车继续...")
    
    # 获取目标颜色
    target_color, confidence, detection_info = detector.get_dominant_color_at_center()
    if not target_color:
        print("❌ 无法获取目标颜色")
        return
    
    print(f"✅ 目标颜色设置: RGB{target_color}")
    print(f"   置信度: {confidence:.3f}")
    
    # 显示检测到的所有颜色
    all_colors = detection_info.get('all_colors', [])
    weights = detection_info.get('weights', [])
    print(f"   检测到的所有颜色:")
    for i, (color, weight) in enumerate(zip(all_colors, weights)):
        marker = "👑" if i == 0 else "  "
        print(f"   {marker} RGB{color} (权重: {weight:.3f})")
    
    print(f"\n步骤2: 测试颜色匹配")
    tolerance = 40
    print(f"使用容差: {tolerance}")
    
    # 测试当前位置的匹配
    is_match, match_confidence, match_info = detector.is_color_match_dominant(
        target_color=target_color,
        tolerance=tolerance
    )
    
    current_color = match_info.get('dominant_color', (0, 0, 0))
    color_distance = match_info.get('color_distance', 999)
    
    print(f"当前检测结果:")
    print(f"   当前主要颜色: RGB{current_color}")
    print(f"   颜色距离: {color_distance:.1f}")
    print(f"   匹配结果: {'✅ 匹配' if is_match else '❌ 不匹配'}")
    print(f"   匹配置信度: {match_confidence:.3f}")
    
    print(f"\n步骤3: 实时监控测试")
    print("现在请移动不同颜色到屏幕中心观察检测变化")
    print("按 Ctrl+C 停止监控")
    
    try:
        while True:
            # 检测当前颜色
            is_match, confidence, detection_info = detector.is_color_match_dominant(
                target_color=target_color,
                tolerance=tolerance
            )
            
            current_color = detection_info.get('dominant_color', (0, 0, 0))
            color_distance = detection_info.get('color_distance', 999)
            status = "🎯 匹配" if is_match else "⏳ 监控"
            
            print(f"\r{status} | 目标: RGB{target_color} | 当前: RGB{current_color} | 距离: {color_distance:.1f} | 置信度: {confidence:.3f}   ", 
                  end="", flush=True)
            
            time.sleep(0.2)
            
    except KeyboardInterrupt:
        print(f"\n\n✅ 监控结束")

def debug_app_issue():
    """调试主程序的问题"""
    print("\n🔍 调试主程序颜色检测问题")
    print("=" * 60)
    
    # 模拟主程序的检测逻辑
    from components.color_trigger import ColorTriggerItem
    
    # 创建一个测试触发器
    print("创建测试触发器...")
    trigger_item = ColorTriggerItem(
        name="测试触发器",
        color=(255, 0, 0),  # 红色
        algorithm="RGB",
        tolerance=40
    )
    
    # 设置为主要颜色检测方法
    trigger_item.detection_method = "dominant_kmeans"
    trigger_item.detection_area_width = 200
    trigger_item.kmeans_clusters = 3
    
    print(f"触发器配置:")
    print(f"   名称: {trigger_item.name}")
    print(f"   目标颜色: RGB{trigger_item.color}")
    print(f"   检测方法: {trigger_item.detection_method}")
    print(f"   检测区域: {trigger_item.detection_area_width}x{trigger_item.detection_area_width}")
    print(f"   容差: {trigger_item.tolerance}")
    
    # 模拟主程序的检测逻辑
    from page.home import HomePage
    
    # 创建主页面实例（仅用于测试检测方法）
    print(f"\n测试主程序检测逻辑...")
    
    # 直接测试检测方法
    try:
        from utils.dominant_color_detector import DominantColorDetector
        
        detector = DominantColorDetector(
            region_size=trigger_item.detection_area_width,
            k_clusters=trigger_item.kmeans_clusters,
            cache_duration=0.05
        )
        
        # 获取屏幕中心坐标
        screen_width, screen_height = pyautogui.size()
        center_x, center_y = screen_width // 2, screen_height // 2
        
        print(f"检测位置: ({center_x}, {center_y})")
        
        # 执行检测
        is_match, confidence, detection_info = detector.is_color_match_dominant(
            target_color=trigger_item.color,
            tolerance=trigger_item.tolerance,
            center_x=center_x,
            center_y=center_y,
            region_size=trigger_item.detection_area_width
        )
        
        print(f"检测结果:")
        print(f"   匹配: {'✅ 是' if is_match else '❌ 否'}")
        print(f"   置信度: {confidence:.3f}")
        
        if detection_info.get('dominant_color'):
            dominant_color = detection_info['dominant_color']
            color_distance = detection_info.get('color_distance', 0)
            print(f"   检测到的主要颜色: RGB{dominant_color}")
            print(f"   颜色距离: {color_distance:.1f}")
            
            # 显示所有检测到的颜色
            all_colors = detection_info.get('all_colors', [])
            weights = detection_info.get('weights', [])
            if all_colors and weights:
                print(f"   所有检测到的颜色:")
                for i, (color, weight) in enumerate(zip(all_colors, weights)):
                    marker = "👑" if i == 0 else "  "
                    print(f"   {marker} RGB{color} (权重: {weight:.3f})")
        
    except Exception as e:
        print(f"❌ 检测失败: {e}")
        import traceback
        traceback.print_exc()

def debug_hotkey_issue():
    """调试热键问题"""
    print("\n🔍 调试热键检测问题")
    print("=" * 60)
    
    print("主程序中的颜色检测需要同时满足两个条件:")
    print("1. 颜色匹配成功")
    print("2. 热键被按下 (hotkey_pressed = True)")
    
    print(f"\n检查热键逻辑:")
    print("在主程序的 check_colors_background 方法中:")
    print("```python")
    print("if color_matches:")
    print("    item.color_detected = True")
    print("    # 只有当热键被按下时才触发")
    print("    if getattr(item, 'hotkey_pressed', False):")
    print("        print('热键按下 + 颜色匹配: 立即触发！')")
    print("        self.execute_mouse_left_click(item)")
    print("```")
    
    print(f"\n这意味着:")
    print("- 即使颜色匹配成功，如果没有按下设置的热键，也不会触发左键")
    print("- 需要同时按住热键并且检测到目标颜色才会触发")
    
    print(f"\n建议检查:")
    print("1. 确认热键监听器是否正常工作")
    print("2. 确认在颜色出现时是否按住了设置的热键")
    print("3. 检查热键设置是否正确")

def debug_cache_issue():
    """调试缓存问题"""
    print("\n🔍 调试缓存问题")
    print("=" * 60)
    
    print("demo脚本中可能存在缓存问题:")
    print("DominantColorDetector 使用了缓存机制，可能导致:")
    print("1. 颜色变化后仍然返回缓存的旧颜色")
    print("2. 检测结果不能及时更新")
    
    print(f"\n测试缓存行为:")
    
    # 测试缓存
    detector = DominantColorDetector(region_size=200, k_clusters=3, cache_duration=2.0)  # 2秒缓存
    
    print("第一次检测 (建立缓存):")
    color1, conf1, info1 = detector.get_dominant_color_at_center()
    print(f"   结果: RGB{color1}, 缓存: {info1.get('cached', False)}")
    
    print("立即第二次检测 (应该使用缓存):")
    color2, conf2, info2 = detector.get_dominant_color_at_center()
    print(f"   结果: RGB{color2}, 缓存: {info2.get('cached', False)}")
    
    print("禁用缓存的检测:")
    color3, conf3, info3 = detector.get_dominant_color_at_center(use_cache=False)
    print(f"   结果: RGB{color3}, 缓存: {info3.get('cached', False)}")
    
    print(f"\n建议:")
    print("1. 在demo脚本中使用更短的缓存时间")
    print("2. 或者禁用缓存: use_cache=False")

def main():
    """主函数"""
    print("🚀 颜色检测问题诊断工具")
    print("=" * 60)
    
    print("发现的问题:")
    print("1. demo脚本: 可能存在缓存导致的检测延迟")
    print("2. 主程序: 需要同时满足颜色匹配和热键按下两个条件")
    
    print(f"\n选择调试模式:")
    print("1. 调试 demo 脚本问题")
    print("2. 调试主程序检测逻辑")
    print("3. 调试热键逻辑")
    print("4. 调试缓存问题")
    print("5. 全部调试")
    
    try:
        choice = input("请选择 (1-5): ").strip()
    except:
        choice = "5"
    
    if choice == "1":
        debug_demo_issue()
    elif choice == "2":
        debug_app_issue()
    elif choice == "3":
        debug_hotkey_issue()
    elif choice == "4":
        debug_cache_issue()
    else:
        debug_demo_issue()
        debug_app_issue()
        debug_hotkey_issue()
        debug_cache_issue()

if __name__ == "__main__":
    main()
